package com.ruoyi.kanfang.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.kanfang.domain.BuildingDetailInfo;
import com.ruoyi.kanfang.domain.BuildingDetailReduceLog;
import com.ruoyi.kanfang.domain.BuildingInfo;
import com.ruoyi.kanfang.mapper.BuildingDetailInfoMapper;
import com.ruoyi.kanfang.mapper.BuildingDetailReduceLogMapper;
import com.ruoyi.kanfang.mapper.BuildingInfoMapper;
import com.ruoyi.kanfang.service.IBuildingDetailInfoService;
import com.ruoyi.kanfang.util.BusinessException;
import com.ruoyi.kanfang.util.JsoupConstant;
import com.ruoyi.kanfang.util.JsoupUtils;
import com.ruoyi.kanfang.util.KanFangUrl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商品房信息Service业务层处理
 * 
 * @author limin
 * @date 2024-04-30
 */
@Slf4j
@Service
public class BuildingDetailInfoServiceImpl implements IBuildingDetailInfoService 
{
    @Resource
    private BuildingDetailInfoMapper buildingDetailInfoMapper;

    @Resource
    private BuildingDetailReduceLogMapper buildingDetailReduceLogMapper;

    @Resource
    private BuildingInfoMapper buildingInfoMapper;

    /**
     * 查询商品房信息
     * 
     * @param id 商品房信息主键
     * @return 商品房信息
     */
    @Override
    public BuildingDetailInfo selectBuildingDetailInfoById(Long id)
    {
        return buildingDetailInfoMapper.selectBuildingDetailInfoById(id);
    }

    /**
     * 查询商品房信息列表
     * 
     * @param buildingDetailInfo 商品房信息
     * @return 商品房信息
     */
    @Override
    public List<BuildingDetailInfo> selectBuildingDetailInfoList(BuildingDetailInfo buildingDetailInfo)
    {
        return buildingDetailInfoMapper.selectBuildingDetailInfoList(buildingDetailInfo);
    }

    /**
     * 新增商品房信息
     * 
     * @param buildingDetailInfo 商品房信息
     * @return 结果
     */
    @Override
    public int insertBuildingDetailInfo(BuildingDetailInfo buildingDetailInfo)
    {
        return buildingDetailInfoMapper.insertBuildingDetailInfo(buildingDetailInfo);
    }

    /**
     * 修改商品房信息
     * 
     * @param buildingDetailInfo 商品房信息
     * @return 结果
     */
    @Override
    public int updateBuildingDetailInfo(BuildingDetailInfo buildingDetailInfo)
    {
        return buildingDetailInfoMapper.updateBuildingDetailInfo(buildingDetailInfo);
    }

    /**
     * 批量删除商品房信息
     * 
     * @param ids 需要删除的商品房信息主键
     * @return 结果
     */
    @Override
    public int deleteBuildingDetailInfoByIds(Long[] ids)
    {
        return buildingDetailInfoMapper.deleteBuildingDetailInfoByIds(ids);
    }

    /**
     * 删除商品房信息信息
     * 
     * @param id 商品房信息主键
     * @return 结果
     */
    @Override
    public int deleteBuildingDetailInfoById(Long id)
    {
        return buildingDetailInfoMapper.deleteBuildingDetailInfoById(id);
    }


    @Override
    public AjaxResult initData(String serialNum) {
        if(serialNum == null){
            throw new BusinessException("小区编号不为空");
        }
        BuildingInfo building = buildingInfoMapper.selectBySerialNum(serialNum);
        if(building == null){
            throw new BusinessException("小区不存在");
        }
        boolean flag = true;
        int page = 1,readNum = 0,totalNum = 0;
        List<BuildingDetailInfo> list = new ArrayList<>();
        try{
            while(flag){
                String url = String.format(KanFangUrl.KF_BEIKE_XIAOQU_DETAIL_URL,page, serialNum);
                // 连接网页并获取HTML文档
                Document doc = Jsoup.connect(url).get();
                Element totalEle = doc.selectFirst("h2.total span");
                if(totalEle != null){
                    String totalStr = totalEle.text();
                    if(StringUtils.isNotEmpty(totalStr)&&"0".equals(totalStr)){
                        return AjaxResult.warn("该小区没有二手房");
                    }
                    totalNum = NumberUtils.toInt(totalStr);
                }
                Element element = doc.selectFirst("ul.sellListContent");
                if(element != null){
                    readNum += element.select("li.clear").size();
                    if((totalNum - readNum)>0){
                        page++;
                    }else{
                        flag = false;
                    }
                    element.select("li.clear").forEach(li -> {
                        BuildingDetailInfo info = new BuildingDetailInfo();
                        info.setBuildingName(building.getBuildingName());
                        Element imgEle = li.selectFirst("a.img");
                        String detailUrl = JsoupUtils.getAttr(imgEle, JsoupConstant.ATTR_HREF);
                        String title = JsoupUtils.getAttr(imgEle, JsoupConstant.ATTR_TITLE);
                        info.setBuildingDetailUrl(detailUrl);
                        info.setSellName(title);
                        info.setTitle(title);
                        if(StringUtils.isNotEmpty(detailUrl)){
                            //https://ganzhou.ke.com/ershoufang/103130016621.html 截取出数字部分
                            String detailSerialNum = detailUrl.substring(detailUrl.lastIndexOf("/") + 1, detailUrl.lastIndexOf("."));
                            info.setSerialNum(detailSerialNum);
                        }
                        //tag
                        Element tag = li.selectFirst("div.info div.title img");
                        if(tag != null){
                            String src = JsoupUtils.getAttr(tag, JsoupConstant.ATTR_SRC);
                            if(StringUtils.isNotEmpty(src)&&src.contains("bikanhaofang")){
                                info.setTag("好赞好房");
                            }
                        }
                        Element houseInfo = li.selectFirst("div.houseInfo");
                        String ownText = JsoupUtils.getOwnText(houseInfo);
                        if(StringUtils.isNotEmpty(ownText)){
                            info.setHouseInfo(ownText);
                        }
                        Element followInfo = li.selectFirst("div.followInfo");
                        String starInfo = JsoupUtils.getOwnText(followInfo);
                        if(StringUtils.isNotEmpty(starInfo)){
    //                        40人关注 / 1年前发布
                            String starNum = starInfo.substring(0, starInfo.indexOf("人"));
                            if(NumberUtils.isDigits(starNum)){
                                info.setStarNum(Long.valueOf(starNum));
                            }
                        }
                        Element flgEle = li.selectFirst("div.tag");
                        if(flgEle != null && flgEle.select("span") != null){
                            flgEle.select("span").forEach(span -> {
                                if(span.hasClass("two")){
                                    info.setTwoFlg(1);
                                }
                                if(span.hasClass("taxfree")){
                                    info.setFiveFlg(1);
                                }
                            });
                        }
                        Element priceElement = li.selectFirst("div.priceInfo");
                        if(priceElement != null && priceElement.select("div") != null){
                            priceElement.select("div").forEach(div -> {
                                if(div.hasClass("totalPrice") && div.selectFirst("span") != null){
                                    String totalPrice = JsoupUtils.getOwnText(div.selectFirst("span"));
                                    info.setTotalFee(new BigDecimal(totalPrice));
                                }
                                if(div.hasClass("unitPrice") && div.selectFirst("span") != null){
                                    String unitPrice = JsoupUtils.getOwnText(div.selectFirst("span"));
                                    if(StringUtils.isNotEmpty(unitPrice)&&unitPrice.contains("/")){
                                        info.setUnitPrice(new BigDecimal(unitPrice.split("/")[0]
                                                .replace(",","").replace("元", "")));
                                    }
                                }
                            });
                        }
                        if(StringUtils.isNotEmpty(title)){
                            if(title.contains("满五唯一")){
                                info.setFiveFlg(1);
                                info.setOnlyFlg(1);
                            }
                        }
                        info.setSource(building.getSource());
                        list.add(info);
                    });
                }else {
                    flag = false;
                }
            }

            Date date = new Date();
            if(CollectionUtils.isNotEmpty(list)){
                list.forEach(info -> {
                    //判断是否已存在
                    BuildingDetailInfo old = buildingDetailInfoMapper.selectBySerialNum(info.getSerialNum());
                    if(old == null){
                        info.setCreateTm(date);
                        info.setUpdateTm(date);
                        buildingDetailInfoMapper.insertBuildingDetailInfo(info);
                    }else{
                        if(!Objects.equals(old.getSellName(),info.getSellName())
                                ||!Objects.equals(old.getTotalFee(),info.getTotalFee())){
                            if(old.getTotalFee()!=null && info.getTotalFee() != null &&
                                    old.getTotalFee().compareTo(info.getTotalFee()) != 0){
                                //降价
                                BigDecimal reduce = old.getTotalFee().subtract(info.getTotalFee());
                                BuildingDetailReduceLog reduceLog = new BuildingDetailReduceLog();
                                reduceLog.setDetailId(old.getId());
                                reduceLog.setOriginPrice(old.getTotalFee());
                                reduceLog.setReducePrice(reduce);
                                reduceLog.setCurrentPrice(info.getTotalFee());
                                reduceLog.setCreateTm(date);

                                old.setPriceReduce(reduce);
                                old.setReduceTm(date);
                                buildingDetailReduceLogMapper.insertBuildingDetailReduceLog(reduceLog);
                            }
                            old.setSellName(info.getSellName());
                            old.setTotalFee(info.getTotalFee());
                            old.setUpdateTm(date);
                            old.setUnitPrice(info.getUnitPrice());
                            old.setStarNum(info.getStarNum());
                            buildingDetailInfoMapper.updateBuildingDetailInfo(old);
                        }
                    }
                });
            }
        }catch (Exception e){
            log.error("com.ruoyi.kanfang.service.impl.BuildingDetailInfoServiceImpl.initData 系统异常", e);
            return AjaxResult.error("系统异常");
        }
        return AjaxResult.success();
    }

    @Override
    public void dataProcess() {
        List<BuildingDetailInfo> list = buildingDetailInfoMapper.selectForProcess();
        if(CollectionUtils.isEmpty(list)){
            return ;
        }
        Date nowDate = DateUtils.getNowDate();
        list.forEach(info -> {
            String houseInfo = info.getHouseInfo();
            if(StringUtils.isEmpty(houseInfo)){
                return;
            }
            String[] arr = houseInfo.split("\\|");
            if(arr.length == 3){
                floorType(arr[0], info);
                unitArea(arr[1],info);
                facing(arr[2],info);
                info.setUpdateTm(nowDate);
                buildingDetailInfoMapper.updateBuildingDetailInfo(info);
            }
        });
    }

    private void floorType(String str, BuildingDetailInfo info){
        if(StringUtils.isNotEmpty(str)){
            if(str.contains("中楼层")){
                info.setFloorType("中楼层");
            }else if(str.contains("低楼层")){
                info.setFloorType("低楼层");
            }else if(str.contains("高楼层")){
                info.setFloorType("高楼层");
            }
        }
        if(str.contains("(") && str.contains(")")){
            //截取括号内容
            String floorCount = StringUtils.substringBetween(str, "共", "层");
            if(StringUtils.isNotEmpty(floorCount)){
                info.setFloorCount(floorCount);
            }
            //截取)后内容
            String houseType = str.substring(str.indexOf(")") + 1);
            if(StringUtils.isNotEmpty(houseType)){
                info.setHouseType(houseType.trim());
            }
        }
    }

    private void unitArea(String str, BuildingDetailInfo info){
        if(StringUtils.isNotEmpty(str)){
            if(str.contains("平米")){
                String unitArea = str.replace("平米", "");
                if(StringUtils.isNotEmpty(unitArea)){
                    info.setUnitArea(new BigDecimal(unitArea.trim()));
                }
            }
        }
    }

    private void facing(String str, BuildingDetailInfo info){
        if(StringUtils.isNotEmpty(str)){
            str = str.trim();
            if(str.contains("东") || str.contains("西") || str.contains("南") || str.contains("北")){
                info.setFacing(str);
            }
        }
    }

}
